package 线程池.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/4/24 13:49
 * @description:计算完成时方法（完成回调与感知异常
 * @version:
 */
public class ShowThread3 {
    //创建线程池  第一个参数代表核心线程数
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main....start....");

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);//加上 sleep() 是为了让输出结果更明显
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).whenCompleteAsync((res,exception) -> {
            //异步任务执行完成的回调
            System.out.println("异步任务执行完成。。。结果为：" + res + " 异常为：" + exception);
        }).exceptionally(throwable -> {
            //一步任务执行失败的回调，同时可以指定返回值
            return 10;
        });
        //future.get方法可以阻塞等待线程执行完毕
        Integer ans = future.get();
        System.out.println("最后输出结果为:" + ans);
        System.out.println("main....end....");
    }
}
